
package com.example.wirelessapp;
import java.sql.SQLException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class myDBClass{
	public static final String KEY_NAME = "UserName";
	public static final String KEY_AGE = "UserAge";
	public static final String KEY_BLOODTYPE = "UserBlood";

	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "UserDB";
	private static final String DATABASE_TABLE = "profile";

	private static final String DATABASE_CREATE = "create table profile"
			+ "(UserName text, UserAge numeric, UserBlood text);"; 
	private Context context = null;
	private myDBClassHelper DBHelper;
	private SQLiteDatabase db;
	
	public myDBClass(Context ctx){
		this.context = ctx;
		DBHelper = new myDBClassHelper(context);
	}
	
	//the following is used to open/close the using of DB
	public myDBClass open() throws SQLException{
		db = DBHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		DBHelper.close();
	}
	
	//the following are used for insert/delete/update table
	public long insertProfile(String UserName, String UserAge, String UserBlood){
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NAME, UserName);
		initialValues.put(KEY_AGE, UserAge);
		initialValues.put(KEY_BLOODTYPE, UserBlood);
		return db.insert(DATABASE_TABLE, null, initialValues);
	}
	public boolean deleteProfile(long rowId){
		return db.delete(DATABASE_TABLE,KEY_NAME + "=" + rowId,null) > 0;
	}
	public boolean updateProfile(long rowId, String UserName, String UserAge, String UserBlood){
		ContentValues args = new ContentValues();
		args.put(KEY_NAME, UserName);
		args.put(KEY_AGE, UserAge);
		args.put(KEY_BLOODTYPE, UserBlood);
		return db.update(DATABASE_TABLE, args,KEY_NAME + "=" + rowId,null) > 0;
	}
	
	//the following is used for asking for and data in DB
	public Cursor getAllProfile(){
		return db.query(DATABASE_TABLE, new String[] {
			KEY_NAME,
			KEY_AGE,
			KEY_BLOODTYPE},
			null,
			null,
			null,
			null,
			null);
	}
		
	//the following is used to connect with DB (needed)
	public class myDBClassHelper extends SQLiteOpenHelper { 
	 myDBClassHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
	
		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(UserName TEXT(100)," + " UserAge TEXT(3)," + " UserBlood TEXT(2));");
			Log.d("CREATE TABLE","Create Table Successfully.");
		}
	
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w("Example",
					"Upgrading database, this will drop tables and recreate.");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
			}
		
	}

}
